<?php
/*
Plugin Name: ArchivePress
Plugin URI: http://code.google.com/p/archivepress/
Description: Archiving blogs with blogs.
Version: 1.0.0
Author: University of London Computer Centre
Author URI: http://code.google.com/p/archivepress/
License: GPL2
*/
?>

<?php
	ini_set("display_errors","0");
// constants
	define('ARCHIVEPRESS','archivepress');
	// Pre-2.6 compatibility
	if ( ! defined( 'WP_PLUGIN_DIR' ) )
		define( 'WP_PLUGIN_DIR', WP_CONTENT_DIR . '/plugins' );
	// ArchivePress plugin directory	
	define( 'WP_ARCHIVEPRESS_DIR', WP_PLUGIN_DIR . '/archivepress' );
	// ArchivePress Prefix
	define( 'WP_ARCHIVEPRESS_PREFIX', 'arpr_' );
	
// configuration & dependencies
	// Internationalization 
	load_plugin_textdomain( ARCHIVEPRESS, WP_ARCHIVEPRESS_DIR );
		
	require_once(WP_ARCHIVEPRESS_DIR . '/archivepress.conf.php' );
	global $ArchivePress;

// cron functions
	// web and unix cron
	add_action('init', 'arpr_unix_or_web_fetch');
	function arpr_unix_or_web_fetch() {
		require_once(WP_ARCHIVEPRESS_DIR . '/archivepress.cron.php');
	}
	// wpcron
	add_action('plugins_loaded', 'arpr_wp_fetch');
	function arpr_wp_fetch() {
		global $ArchivePressLog;
		global $ArchivePress;
		// esecute script
		$ArchivePressLog->logIt(ArchivePressLog::LOG_BASIC,__("Cron job started successfully.",ARCHIVEPRESS));
		
		// get active feeds 
		$activeFeeds = array();
		$activeFeeds = $ArchivePress->getFeeds(true,false);
		foreach($activeFeeds as $feed){
			// check if I have to fetch the feed
			if( (time() - strtotime($feed["last_update"])) >= (int)$feed["interval"] ) {
				$ArchivePressLog->logIt(ArchivePressLog::LOG_BASIC,sprintf(__("Fetching feed %s (%s)> posts added: %d ",ARCHIVEPRESS),$feed["name"],$feed["url"],$ArchivePress->fetchFeed($feed)));
			}
		}
	}
	
// Activate, Deactivate, Update and Remove Hooks
	function arpr_activate() {
		// wpcron ON
		wp_schedule_event(time()-8000, 'hourly', 'plugins_loaded');
		
		require(ABSPATH . 'wp-content/plugins/archivepress/archivepress.conf.php');
		$ArchivePress->Activate();
	}
	register_activation_hook( __FILE__, 'arpr_activate' );	
	function arpr_deactivate() {
		// wpcron OFF
		wp_clear_scheduled_hook('archivepress_wp_cron');
		
		require(ABSPATH . 'wp-content/plugins/archivepress/archivepress.conf.php');
		$ArchivePress->Deactivate();
	}
	register_deactivation_hook( __FILE__, 'arpr_deactivate' );
	function arpr_remove() {
		// wpcron OFF
		wp_clear_scheduled_hook('archivepress_wp_cron');
		
		require(ABSPATH . 'wp-content/plugins/archivepress/archivepress.conf.php');
		$ArchivePress->Remove();
	}	
	register_uninstall_hook(__FILE__, 'arpr_remove');

	
	
// WordPress Admin Area Pages
	add_action('admin_menu', WP_ARCHIVEPRESS_PREFIX . 'add_pages');
	function arpr_add_pages() {
	    // New Top Level Menu
	    add_menu_page('ArchivePress', 'ArchivePress', 'administrator', WP_ARCHIVEPRESS_DIR . '/archivepress.php', WP_ARCHIVEPRESS_PREFIX . 'toplevel_page');
	    // Submenus
	    //add_submenu_page('ArchivePress', 'Basic Options', 'Basic Options', 'administrator', 'sub-page', 'mt_sublevel_page');
	
	}	
	function arpr_toplevel_page(){
		// globals
		global $ArchivePress;
		global $ArchivePressLog;
	
		// DISPLAY FEEDS
		// GET ACTIVE FEEDS
		$activeFeeds = array();
		$activeFeeds = $ArchivePress->getFeeds(false,false);
		echo "<form action='' method='post'>
				<input type='hidden' value='yes' name='update' />
				<table cellpadding='5' cellspacing='10'>
				<tr style='font-weight:bold;'><td>Feed Name</td><td>Feed Original url</td><td>Last Update</td><td>Manual update</td></tr>";
		foreach($activeFeeds as $feed){
			if($feed["is_comment"] == "no")
				echo "<tr><td>".$feed["name"]."</td><td>".$feed["url"]."</td><td>".$feed["last_update"]."</td><td><input type='submit' value='Update' name='update_".$feed["id"]."' /> <input type='submit' value='Update Comments' name='updatecomments_".$feed["id"]."' /></td></tr>";
		}
		echo "</table></form>";
		// UPDATE FEEDS MANUALLY
		if(isset($_POST["update"])) {
			foreach($activeFeeds as $feed){
				if(isset($_POST['update_'.$feed["id"]])) {
					$ArchivePressLog->logIt(ArchivePressLog::LOG_BASIC,sprintf(__("Fetching feed %s (%s)> posts added: %d ",ARCHIVEPRESS),$feed["name"],$feed["url"],$ArchivePress->fetchFeed($feed)));
				}
				if(isset($_POST['updatecomments_'.$feed["id"]])) {
					// eventually fetch comments
					$ArchivePressLog->logIt(ArchivePressLog::LOG_BASIC,sprintf(__("Fetching feed %s (%s)> posts added: %d ",ARCHIVEPRESS),$feed["name"],$feed["url"],$ArchivePress->fetchFeedComments($feed["id"])));
				}
			}
		}
		
		echo "<br /><br /><br />";
		
		
		// ADD feeds
		echo "<form action='' method='post'>
				<table cellpadding='5' cellspacing='10'>
				<tr><td>Feed Name</td><td><input type='text' value='Feed Name' name='name' /></td></tr>
				<tr><td>Feed or website url</td><td><input type='text' value='http://' name='url' /></td></tr>
				<tr><td colspan='2'><input type='submit' value='Add Feed' name='add' /></td></tr>
				";
	
		echo "</table></form>";
		if(isset($_POST["add"])) {
			// these are texts!
			//$testURL = "http://digitalcuration.blogspot.com/";
			//$testURL = "http://digitalcuration.blogspot.com/feeds/posts/default";
			//$testURL = "http://digitalcuration.blogspot.com/feeds/posts/default?alt=rss";
			//$testURL = "http://wesleyanargus.com/2010/02/19/%E2%80%9Cdr-horrible%E2%80%9D-a-terrifyingly-successful-campus-production/";
			//$testNAME = "Digital Curation";
			$testURL = $_POST["url"];
			$testNAME = $_POST["name"];
			
			$feedAdded = false;
			$lastSentence = "";
			// ADD NEW FEED PROCEDURE
			// check if is a feed url
			try {
				if($ArchivePress->isFeed($testURL)){
					try {
						$ArchivePress->addLastCheckedFeed($testNAME,true);
						$feedAdded = true;
						$lastSentence = "DISPLAY SUCCESS: feed successfully added";
					} catch (Exception $e) {
						$lastSentence = $e->getMessage();
						$feedAdded = false;
					}
				} else {
					// try autodiscovery
					$feeds = array();
					try {
						$feeds = FeedAutoDiscovery::getFeedLinks($testURL);
						// If the feed was not already added
						if($ArchivePress->isFeedNew($feeds)) {
							// Add Feed
							try {
								$ArchivePress->addFeed($feeds,$testURL,$testNAME);
								$feedAdded = true;
								$lastSentence = "DISPLAY SUCCESS: feed successfully added";
							} catch (Exception $e) {
								$lastSentence = $e->getMessage();
								$feedAdded = false;
							}
						} else {
							$lastSentence = "DISPLAY ERROR: feed already added!";
						}
					} catch (Exception $e) {
						$lastSentence = $e->getMessage();
						$feedAdded = false;
					}
				}
			} catch (Exception $e) {
				// page not found or other curl errors
				$lastSentence = $e->getMessage();
				$feedAdded = false;
			}
			echo $lastSentence."<br><br><br>";
			
	
		}
		echo "<br /><br /><br />";


		
		
/*		TYPEPAD GRAB COMMENTS PROCEDURE
		
		
		//$url = "http://theblackbirdsings.typepad.com/the_blackbird_sings/2010/03/new-work-recent-pieces.html";
		//$url = "http://myloveforyou.typepad.com/my_love_for_you/2010/03/jason-daquino.html";
		//$url = "http://thescenestar.typepad.com/ss/2010/03/contest-little-boots-w-dragonette-glass-house.html";
		$url = "http://gladwell.typepad.com/gladwellcom/2009/12/pinker-round-two-.html";
		
		// prepare content
			$content = file_get_contents($url);
			$xml = new DOMDocument();
			$xml->preserveWhiteSpace = false;
			$xml->formatOutput = false;
			$content = str_replace("\r\n", "", $content);
			$content = str_replace("\n", "", $content);
			@$xml->loadHTML($content);
			
			$commentDiv = $xml->getElementById("comments-content");
		
			if($commentDiv){
				foreach($commentDiv->getElementsByTagName("span") as $content){
					echo $content->textContent."<br>";
					$parentNode = $content->parentNode->parentNode;
					foreach($parentNode->getElementsByTagName("p") as $footer){
						if($footer->getAttribute("class") == "comment-footer"){
							$user = "";
							$date = "";
							if($footer->getElementsByTagName("a")->length == 2){
								$user = $footer->getElementsByTagName("a")->item(0)->textContent;
								$date = $footer->getElementsByTagName("a")->item(1)->textContent;
							} else {
								$date = $footer->getElementsByTagName("a")->item(0)->textContent;
								$user = $footer->textContent;
								$user = str_replace($date,"",$user);
								$user = str_replace("|","",$user);
								$tmp = explode(":",$user);
								if(count($tmp) >= 2){
									$user = trim($tmp[1]);
								} else {
									$user = __("Anonymous",ARCHIVEPRESS);
								}
							}
							
							echo $user." : ".$date."<br><br>";
						}
					}
				}
			}
			
*/			
			
			
/*		
		// GET ACTIVE FEEDS
		$activeFeeds = array();
		$activeFeeds = $ArchivePress->getFeeds(true,false);
		foreach($activeFeeds as $feed){
			echo $feed["id"]." ".$feed["name"]." ".$feed["url"]."<br>";
		}
	
		// FETCH FEEDS
		$activeFeeds = array();
		$activeFeeds = $ArchivePress->getFeeds(true,false);
		foreach($activeFeeds as $feed){
			echo $ArchivePress->fetchFeed($feed);
		}
*/					
	}
	
	
		
	
// Template tags definition	
	function arpr_tag(){
	}
?>